<template>
  <div>
    <el-upload
        class="upload-excel"
        :action="uploadUrl"
        :on-success="handleSuccess"
        :on-error="handleError"
        :before-upload="beforeUpload"
        :headers="uploadHeaders"
        :show-file-list="true"
        accept=".xlsx,.xls"
        name="file"
    >
      <el-button type="primary">上传 Excel 文件</el-button>

      <el-select
          v-if="typeAll"
          v-model="currShop"
          @change="changeShop"
          placeholder="请选择商品"
          style="position: relative; left: 30%;"
      >
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </el-upload>

    <el-button
        type="success"
        @click="onTypechange"
        style="position: relative; left: 50%; top: -60px"
    >
      切换数据形势
    </el-button>

    <div v-if="typeAll">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="dateTime" label="日期" width="200" />
        <el-table-column prop="saleAmount" label="销售金额" width="100" />
        <el-table-column prop="quantity" label="支付件数" width="100" />
        <el-table-column prop="payBuyerNum" label="支付买家数" width="100" />
        <el-table-column prop="refundAmount" label="退款金额" width="100" />
        <el-table-column prop="refundQuantity" label="退款件数" width="100" />
        <el-table-column prop="totalFreight" label="总运费" width="100" />
        <el-table-column prop="cost" label="成本" width="100" />
        <el-table-column prop="profit" label="利润" width="100" />
        <el-table-column prop="ProductTitle" label="宝贝名称" width="250" />
      </el-table>
    </div>

    <div v-else>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="dateTimeFW" label="日期" width="200" />
        <el-table-column prop="saleAmount" label="销售金额" width="100" />
        <el-table-column prop="quantity" label="支付件数" width="100" />
        <el-table-column prop="payBuyerNum" label="支付买家数" width="100" />
        <el-table-column prop="refundAmount" label="退款金额" width="100" />
        <el-table-column prop="refundQuantity" label="退款件数" width="100" />
        <el-table-column label="退款比例" width="100">
          <template #default="{ row }">
            <!-- 假设用退款金额 ÷ 销售金额 -->
            {{ row.saleAmount ? ((row.refundAmount / row.saleAmount) * 100).toFixed(2) + '%' : '0%' }}
          </template>
        </el-table-column>
        <el-table-column prop="totalFreight" label="总运费" width="100" />
        <el-table-column prop="cost" label="成本" width="100" />
        <el-table-column prop="profit" label="利润" width="100" />
        <el-table-column prop="productTitle" label="宝贝名称" width="250" />
        <el-table-column prop="productId" label="宝贝ID" width="100" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'

const apiBaseUrl = ref(import.meta.env.VITE_API_BASE_URL)
// 如果 token 存在，则将其加到请求头
const token = localStorage.getItem('token');

// 上传地址和请求头
const uploadUrl = apiBaseUrl.value + '/taoBaoData/statisticsTaoBaoOrderHistory'
const uploadHeaders = {
  Authorization: token
}

// 响应数据和状态管理
const tableData = ref([])
const options = ref([])
const currShop = ref('')
const allShopData = ref({})
const typeAll = ref(false)

// 上传前校验
const beforeUpload = (file) => {
  const isExcel =
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件（.xlsx/.xls）')
  }
  return isExcel
}

// 上传成功回调
const handleSuccess = (response) => {
  ElMessage.success('上传成功')
  const shopArr = []

  for (const key in response.data) {
    if (response.data.hasOwnProperty(key)) {
      const dataArr = response.data[key]
      if (dataArr[0]) {
        shopArr.push({
          label: dataArr[dataArr.length - 1].ProductTitle,
          value: key
        })
      }
    }
  }

  options.value = shopArr
  allShopData.value = response

  if (!typeAll.value) {
    tableData.value = response.total
  }

  console.log('上传结果:', response)
}

// 上传失败回调
const handleError = (err) => {
  ElMessage.error('上传失败')
  console.error('上传错误:', err)
}

// 切换商品时更新表格
const changeShop = (shop) => {
  console.log('选择的商品:', shop)
  tableData.value = allShopData.value.data[shop]
}

// 切换视图数据类型
const onTypechange = () => {
  typeAll.value = !typeAll.value
  if (!typeAll.value) {
    tableData.value = allShopData.value.total
  }
}
</script>

<style scoped>
.upload-excel {
  margin: 20px;
}
</style>
